<template>
  <div class="edit-popup">
    <popup
        ref="popupRef"
        :title="popupTitle"
        :async="true"
        width="550px"
        :clickModalClose="true"
        @confirm="handleSubmit"
        @close="handleClose"
    >
      <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules">
        <el-form-item label="版本名称" prop="versionName">
          <el-input v-model="formData.versionName" placeholder="请输入版本名称"/>
        </el-form-item>
        <el-form-item label="平台类型" prop="platformType">
          <el-select v-model="formData.versionType" placeholder="请选择平台类型">
            <el-option label="安卓" value="0"></el-option>
            <el-option label="ios" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新内容" prop="versionUpdateContent">
          <el-input v-model="formData.versionUpdateContent" placeholder="请输入版本更新内容"/>
        </el-form-item>
        <el-form-item label="下载地址" prop="downloadAddress">
          <el-input type="textarea" v-model="formData.downloadAddress" placeholder="请输入下载地址" class="xiazai" rows="4"/>
          <!--加一个上传apk-->
          <el-upload
              ref="uploadRef"
              class="upload-demo"
              :action="uploadUrl"
              :auto-upload="true"
              :headers="headers"
              @success="handleUploadSuccess"
              :show-file-list="false"
          >
            <template #trigger>
              <el-button type="primary">上传apk</el-button>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="versionStatus">
          <el-radio-group v-model="formData.versionStatus" placeholder="请选择暂不发布/发布">
            <el-radio
                v-for="(item, index) in dictData.数字类型"
                :key="index"
                :label="parseInt(item.value)"
                :disabled="!item.status"
            >
              {{ item.name }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </popup>
  </div>
</template>
<script lang="ts" setup>
import type {FormInstance} from 'element-plus'
import {informationEdit, informationAdd, informationDetail} from '@/api/information'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type {PropType} from 'vue'
import {getToken} from "@/utils/auth";
import config from "@/config";

const uploadUrl = ref(config.baseUrl+'api/information/uploadApk');

const token = getToken()
const headers = ref({token});
defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑app版本信息' : '新增app版本信息'
})

const formData = reactive({
  versionId: '',
  versionName: '',
  versionType: '',
  versionUpdateContent: '',
  downloadAddress: '',
  versionStatus: '',
})

const formRules = {
  versionType: [
    {
      required: true,
      message: '请选择平台类型',
      trigger: ['change']
    }
  ],
  versionName: [
    {
      required: true,
      message: '请输入版本名称',
      trigger: ['blur']
    }
  ],
  versionUpdateContent: [
    {
      required: true,
      message: '请输入版本更新内容',
      trigger: ['blur']
    }
  ],
  downloadAddress: [
    {
      required: true,
      message: '请输入下载地址',
      trigger: ['blur']
    }
  ],
  versionStatus: [
    {
      required: true,
      message: '请选择暂不发布/发布',
      trigger: ['blur']
    }
  ],
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  const data: any = {...formData}
  mode.value == 'edit' ? await informationEdit(data) : await informationAdd(data)
  popupRef.value?.close()
  feedback.msgSuccess('操作成功')
  emit('success')
}

const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

// const setFormData = async (data: Record<string, any>) => {
//   for (const key in formData) {
//     if (data[key] != null && data[key] != undefined) {
//       //@ts-ignore
//       formData[key] = data[key]
//     }
//   }
// }
const setFormData = async (data: Record<string, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      if (key === 'versionType') {
        // 将数字转换为文本并赋值
        formData.versionType = data[key] === 0 ? '安卓' : data[key] === 1 ? 'iOS' : '';
      } else {
        //@ts-ignore
        formData[key] = data[key];
      }
    }
  }
}

const getDetail = async (row: Record<string, any>) => {
  const data = await informationDetail({
    id: row.versionId
  })
  setFormData(data)
}

const handleClose = () => {
  emit('close')
}
//上传后赋值地址
const handleUploadSuccess = (response: any, file: any, fileList: any) => {
  // 获取上传成功后的地址数据
  const downloadUrl = response.data;

  // 将地址数据赋值给下载地址框
  formData.downloadAddress = downloadUrl;
  feedback.msgSuccess('上传成功')
}

defineExpose({
  open,
  setFormData,
  getDetail
})
</script>
<style>
.xiazai{
  width: 250px;
}
</style>
